package com.gxar.marketdelivery.domain.factory;

import com.gxar.marketdelivery.application.context.DeliveryContext;
import com.gxar.marketdelivery.domain.aviator.parser.MaterialParser;
import com.gxar.marketdelivery.shared.model.BaseDeliveryModel;
import com.gxar.marketdelivery.shared.model.DeliveryMaterialModel;
import com.gxar.marketdelivery.shared.utils.CollectionUtils;
import com.gxar.marketdelivery.shared.utils.ExtractUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author nice
 * @version 1.0
 * @created 2023/7/20.
 */
@Service
public class MaterialFactory {

    public Map<Long, String> parseMaterial(DeliveryContext context, List<? extends BaseDeliveryModel> deliveryModels) {
        Map<Long, DeliveryMaterialModel> materialMap = deliveryModels.stream()
                .filter(deliveryModel -> deliveryModel.getMaterialModel() != null)
                .collect(Collectors.toMap(BaseDeliveryModel::getId, BaseDeliveryModel::getMaterialModel));
        //物料解析
        List<DeliveryMaterialModel> materialModels = ExtractUtils.extractField(deliveryModels, (deliveryModel) -> {
            return materialMap.getOrDefault(deliveryModel.getId(), deliveryModel.getMaterialModel());
        });
        if (CollectionUtils.isEmpty(materialModels)) {
            return Collections.emptyMap();
        }

        Map<Long, String> returnMap = new HashMap<>();
        Map<Long, String> targetMaterialMap = MaterialParser.parse(context, materialModels);
        deliveryModels.forEach((deliveryModel) -> {
            Long targetId = deliveryModel.getId();
            if (targetMaterialMap.containsKey(targetId)) {
                returnMap.put(deliveryModel.getId(), targetMaterialMap.get(targetId));
            }
        });
        return returnMap;
    }
}
